package com.wmx.datastructuresandalgorithms;

import java.util.Arrays;

public class MyStack {
    private int [] array;
    private int maxSize;
    private int top ;

    MyStack(){
        this.array =  new int[50];
        this.maxSize = 50 ;
        this.top = -1;
    }

    MyStack(int size){
        if(size < 0){
            throw new IllegalArgumentException("栈初始容量不能小于0: "+size);
        }
        this.array =  new int[size];
        this.maxSize = size ;
        this.top = -1;
    }

   //压栈

    public boolean push (int value){
        if(top < maxSize-1){
            array[++top] = value;
            return true;
        }else {
            return false;
        }
    }

    //自动扩容
    public boolean autoPush (int value){

        isGrow(top+1);
        array[++top] =  value;
        return true;
    }


   //出栈
    public  int pop(int value){
       return  array[top--];
    }


    //访问栈顶数据
    public int peek(){
        return array[top];
    }

    //判断栈是否为空
    public boolean isEmpty(){
        return (top == -1);
    }

    //判断栈是否满了
    public boolean isFull(){
        return (top == maxSize-1);
    }

    /**
     * 是否需要扩容，如果需要，则扩大一倍并返回true，不需要则返回false
     * @param minCapacity
     * @return
     */
    public boolean isGrow(int minCapacity){
        int oldCapacity = maxSize;
        //如果当前元素压入栈之后总容量大于前面定义的容量，则需要扩容
        if(minCapacity >= oldCapacity){
            //定义扩大之后栈的总容量
            int newCapacity = 0;
            //栈容量扩大两倍(左移一位)看是否超过int类型所表示的最大范围
            if((oldCapacity<<1) - Integer.MAX_VALUE >0){
                newCapacity = Integer.MAX_VALUE;
            }else{
                newCapacity = (oldCapacity<<1);//左移一位，相当于*2
            }
            this.maxSize = newCapacity;

            array = Arrays.copyOf(array, maxSize);
            return true;
        }else{
            return false;
        }
    }


    public static void main(String[] args) {
        MyStack myStack = new MyStack(3);
        myStack.autoPush(1);
        myStack.autoPush(2);
        myStack.autoPush(3);
        myStack.autoPush(4);
        myStack.autoPush(5);

        System.out.printf("============="+myStack.peek());
    }
}
